﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SGP;
using System.IO;
using System.Xml.Linq;

namespace Tile_Editor
{
    public partial class Form1 : Form
    {
        //Bitmap tileSet = Properties.Resources._default;
        Size mapSize = new Size(10, 10);
        Size tileSize = new Size(64, 64);
        Size tileSet = Size.Empty;

        Tile[,] tileMap = new Tile[10,10];
        Tile selectedTile = null;
        Tile coppiedTile = null;
        string fileName = "";
        string filePath = "";
        List<Tile> selectedTiles = new List<Tile>();
        float scale = 1.0f;
        Point mapPos = new Point(0, 0);
        Point tileSetPos = new Point(0, 0);

        private OpenFileDialog openFileDialog;
        private OpenFileDialog loadMapDialog;
        private SaveFileDialog saveMapDialog;
        private FolderBrowserDialog folderDialog;

        int imageID = -1;

        bool running = true;
        bool paintTool = true;
        bool mouseIsDown = false;

        public bool Running
        {
            get { return running; }
            set { running = value; }
        }

        ManagedDirect3D d3d = null;
        ManagedTextureManager texture = null;

        public Form1()
        {
            InitializeComponent();
            InitD3D();
            InitInterface();
        }

        public bool GetFilePath()
        {
            this.folderDialog = new System.Windows.Forms.FolderBrowserDialog();

            folderDialog.Description = "Select a resource folder for images.";

            DialogResult result = folderDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                filePath = folderDialog.SelectedPath;
            }
            else if (result == DialogResult.Cancel)
            {
                return false;
            }

            return true;

        }

        private void InitD3D()
        {
            d3d = ManagedDirect3D.Instance;
            texture = ManagedTextureManager.Instance;
            d3d.InitManagedDirect3D(panel2);
            d3d.InitManagedDirect3D(panel1);
            d3d.InitManagedDirect3D(coppiedPreviewPanel);
            d3d.InitManagedDirect3D(selectedPreviewPanel);
            texture.InitManagedTextureManager(d3d.Device,d3d.Sprite);
           // imageID = texture.LoadTexture(fileName, Color.FromArgb(255,255,255,255).ToArgb());

            for (int x = 0; x < mapSize.Width; x++)
            {
                for (int y = 0; y < mapSize.Height; y++)
                {
                    tileMap[x, y] = new Tile();
                    tileMap[x, y].XPos = x;
                    tileMap[x, y].YPos = y;
                }
            }
        }

        private void InitInterface()
        {
            mapSizeXNumericUpDown.Value = mapSize.Width;
            mapSizeYNumericUpDown.Value = mapSize.Height;
            tileSizeXNumericUpDown.Value = tileSize.Width;
            tileSizeYNumericUpDown.Value = tileSize.Height;
            scaleNumericUpDown.Value = (decimal)(scale);

            coppiedTerrainTypeComboBox.Items.Add("GRASS");
            coppiedTerrainTypeComboBox.Items.Add("DIRT");
            coppiedTerrainTypeComboBox.Items.Add("STONE_FLOOR");
            coppiedTerrainTypeComboBox.Items.Add("STONE_WALL");
            coppiedTerrainTypeComboBox.Items.Add("TREE");
            coppiedTerrainTypeComboBox.Items.Add("WATER");
            coppiedTerrainTypeComboBox.Items.Add("MUD");
            coppiedTerrainTypeComboBox.Items.Add("LAVA");
            coppiedTerrainTypeComboBox.Items.Add("ROCKS");
            coppiedTerrainTypeComboBox.Items.Add("MOUNTIAN");
            coppiedTerrainTypeComboBox.Items.Add("SNOW");
            coppiedTerrainTypeComboBox.Items.Add("SHRUB");
            coppiedTerrainTypeComboBox.Items.Add("PILLAR");
            coppiedTerrainTypeComboBox.Items.Add("CROWD");
            coppiedTerrainTypeComboBox.SelectedItem = null;
            
            selectedTerrainTypeComboBox.Items.Add("GRASS");
            selectedTerrainTypeComboBox.Items.Add("DIRT");
            selectedTerrainTypeComboBox.Items.Add("STONE_FLOOR");
            selectedTerrainTypeComboBox.Items.Add("STONE_WALL");
            selectedTerrainTypeComboBox.Items.Add("TREE");
            selectedTerrainTypeComboBox.Items.Add("WATER");
            selectedTerrainTypeComboBox.Items.Add("MUD");
            selectedTerrainTypeComboBox.Items.Add("LAVA");
            selectedTerrainTypeComboBox.Items.Add("ROCKS");
            selectedTerrainTypeComboBox.Items.Add("MOUNTIAN");
            selectedTerrainTypeComboBox.Items.Add("SNOW");
            selectedTerrainTypeComboBox.Items.Add("SHRUB");
            selectedTerrainTypeComboBox.Items.Add("PILLAR");
            selectedTerrainTypeComboBox.Items.Add("CROWD");
            selectedTerrainTypeComboBox.SelectedItem = null;

            coppiedEventComboBox.Items.Add("playerSpawnPoint");
            coppiedEventComboBox.Items.Add("enemySpawnPoint");
            coppiedEventComboBox.Items.Add("winCondition");
            coppiedEventComboBox.Items.Add("lossCondition");
            coppiedEventComboBox.SelectedItem = null;

            selectedEventComboBox.Items.Add("playerSpawnPoint");
            selectedEventComboBox.Items.Add("enemySpawnPoint");
            selectedEventComboBox.Items.Add("winCondition");
            selectedEventComboBox.Items.Add("lossCondition");
            selectedEventComboBox.SelectedItem = null;

        }

        public void Render()
        {
            RenderLeftPreview();
            RenderRightPreview();
            RenderLeftPanel();
            RenderRightPanel();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            running = false;
        }

        private void importBitmapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.openFileDialog = new System.Windows.Forms.OpenFileDialog();

            openFileDialog.FileName = null;
            openFileDialog.InitialDirectory = filePath;
            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                fileName = openFileDialog.SafeFileName;

                string fullPathAndName = filePath + "\\" + fileName;

                imageID = texture.LoadTexture(fullPathAndName, Color.FromArgb(255, 255, 255, 255).ToArgb());

                tileSet = new Size(texture.GetTextureWidth(imageID) / tileSize.Width, texture.GetTextureHeight(imageID) / tileSize.Height);

                coppiedimageIDNumericUpDown.Maximum = (tileSet.Width * tileSet.Height) - 1;
                selectedImageIDNumericUpDown.Maximum = (tileSet.Width * tileSet.Height) - 1;

                groupBox4.Enabled = true;
                groupBox1.Enabled = true;

                ResizeScrollBars();

            }
        }

        private void RenderLeftPanel()
        {
            d3d.ChangeDisplayParam(panel1);
            d3d.Clear(0, 0, 0);
            d3d.DeviceBegin();

            //d3d.Sprite.Draw2D(, new Point(0, 0), 0.0f, new Point(0, 0), 0);
            if (imageID != -1)
            {
                d3d.SpriteBegin();
                texture.Draw(imageID, tileSetPos.X, tileSetPos.Y, 1.0f, 1.0f, Rectangle.Empty, 0, 0, 0.0f, Color.FromArgb(255, 255, 255, 255).ToArgb());
                d3d.SpriteEnd();

                for (int i = 0; i < tileSet.Width; i++)
                {
                    d3d.DrawLine((tileSize.Width * i) + tileSetPos.X, tileSetPos.Y, (tileSize.Width * i) + tileSetPos.X, (tileSize.Height * tileSize.Height) + tileSetPos.Y, Color.Black, 1.0f);
                }
                for (int i = 0; i < tileSet.Height; i++)
                {
                    d3d.DrawLine(tileSetPos.X, (tileSize.Height * i) + tileSetPos.Y, tileSetPos.X + (tileSet.Width * tileSize.Width), (tileSize.Height * i) + tileSetPos.Y, Color.Black, 1.0f);
                }

                if (coppiedTile != null)
                {
                    int col = 0;
                    int row = 0;

                    for (int i = 0; i < coppiedTile.ImageID; i++)
                    {
                        col++;
                        if (col >= tileSet.Width)
                        {
                            col = 0;
                            row++;
                            if (row >= tileSet.Height)
                            {
                                col = 0;
                                row = 0;
                            }
                        }
                    }

                    Rectangle r = new Rectangle();
                    r.X = (col * tileSize.Width) + tileSetPos.X;
                    r.Y = (row * tileSize.Height) + tileSetPos.Y;
                    r.Width = tileSize.Width;
                    r.Height = tileSize.Height;

                    d3d.DrawEmptyRect(r, Color.Red, 2.0f);

                }

            }

            d3d.DeviceEnd();
            d3d.Present(panel1);
        }

        private void RenderRightPanel()
        {
            d3d.ChangeDisplayParam(panel2);
            d3d.Clear(0, 0, 0);
            d3d.DeviceBegin();


            //d3d.Sprite.Draw2D(, new Point(0, 0), 0.0f, new Point(0, 0), 0);
            if (imageID != -1)
            {
                d3d.SpriteBegin();

                //texture.Draw(imageID, 0, 0, 1.0f, 1.0f, Rectangle.Empty, 0, 0, 0.0f, Color.FromArgb(255, 255, 255, 255).ToArgb());
                for (int x = 0; x < mapSize.Width; x++)
                {
                    for (int y = 0; y < mapSize.Height; y++)
                    {
                        Point p = new Point();
                        p.X = (int)((float)(tileMap[x, y].XPos) * scale * (float)(tileSize.Width)) + (int)((float)(mapPos.X));
                        p.Y = (int)((float)(tileMap[x, y].YPos) * scale * (float)(tileSize.Height)) + (int)((float)(mapPos.Y));
                        //r.Width = tileSize.Width;
                        //r.Height = tileSize.Height;

                        if (p.X > panel2.Width || p.Y > panel2.Height || p.X + (tileSize.Width*scale) < 0 || p.Y + (tileSize.Height*scale) < 0)
                            continue;

                        int col = 0;
                        int row = 0;

                        for(int i = 0; i < tileMap[x,y].ImageID;i++)
	                    {
		                    col++;
		                    if(col >= tileSet.Width)
		                    {
			                    col = 0;
			                    row++;
			                    if(row >= tileSet.Height)
			                    {
				                    col = 0;
				                    row = 0;
			                    }
		                    }
	                    }


                        Rectangle r = new Rectangle();
                        r.X = col * tileSize.Width;
                        r.Y = row * tileSize.Height;
                        r.Width = tileSize.Width;
                        r.Height = tileSize.Height;

                        

                        texture.Draw(imageID, p.X, p.Y, scale, scale, r, 0, 0, 0.0f, 255, 255, 255, 255);

                    }
                }
                d3d.SpriteEnd();


                if (selectedTile != null)
                {
                    Rectangle r = new Rectangle();
                    r.X = (int)((float)(selectedTile.XPos) * scale * (float)(tileSize.Width)) + (int)((float)(mapPos.X));
                    r.Y = (int)((float)(selectedTile.YPos) * scale * (float)(tileSize.Height)) + (int)((float)(mapPos.Y));
                    r.Width = (int)(tileSize.Width * scale);
                    r.Height = (int)(tileSize.Height * scale);
                    d3d.DrawEmptyRect(r, Color.Red, 3.0f);
                    d3d.DrawLine(r.Left, r.Top, r.Right, r.Bottom, Color.Red);
                }

                if (selectedTiles != null)
                {
                    for (int i = 0; i < selectedTiles.Count; i++)
                    {
                        Rectangle r = new Rectangle();
                        r.X = (int)((float)(selectedTiles[i].XPos) * scale * (float)(tileSize.Width)) + (int)((float)(mapPos.X));
                        r.Y = (int)((float)(selectedTiles[i].YPos) * scale * (float)(tileSize.Height)) + (int)((float)(mapPos.Y));
                        r.Width = (int)(tileSize.Width * scale);
                        r.Height = (int)(tileSize.Height * scale);
                        d3d.DrawEmptyRect(r, Color.Red, 3.0f);
                        d3d.DrawLine(r.Left, r.Top, r.Right, r.Bottom, Color.Red);
                    }
                }

            }

            d3d.DeviceEnd();
            d3d.Present(panel2);
        }

        private void RenderLeftPreview()
        {
            d3d.ChangeDisplayParam(coppiedPreviewPanel);
            d3d.Clear(0, 0, 0);
            d3d.DeviceBegin();
            d3d.SpriteBegin();

            //d3d.Sprite.Draw2D(, new Point(0, 0), 0.0f, new Point(0, 0), 0);
            if (imageID != -1 && coppiedTile != null)
            {

                int col = 0;
                int row = 0;

                for (int i = 0; i < coppiedTile.ImageID; i++)
                {
                    col++;
                    if (col >= tileSet.Width)
                    {
                        col = 0;
                        row++;
                        if (row >= tileSet.Height)
                        {
                            col = 0;
                            row = 0;
                        }
                    }
                }


                Rectangle r = new Rectangle();
                r.X = col * tileSize.Width;
                r.Y = row * tileSize.Height;
                r.Width = tileSize.Width;
                r.Height = tileSize.Height;

                float scaleX = (float)(64.0f) / (float)(tileSize.Width);
                float scaleY = (float)(64.0f) / (float)(tileSize.Height);

                texture.Draw(imageID, 0, 0, scaleX, scaleY, r, 0, 0, 0.0f, 255, 255, 255, 255);

            }
            d3d.SpriteEnd();
            d3d.DeviceEnd();
            d3d.Present(coppiedPreviewPanel);
        }

        private void RenderRightPreview()
        {
            d3d.ChangeDisplayParam(selectedPreviewPanel);
            d3d.Clear(0, 0, 0);
            d3d.DeviceBegin();
            d3d.SpriteBegin();

            if (imageID != -1 && selectedTile != null)
            {

                int col = 0;
                int row = 0;

                for (int i = 0; i < selectedTile.ImageID; i++)
                {
                    col++;
                    if (col >= tileSet.Width)
                    {
                        col = 0;
                        row++;
                        if (row >= tileSet.Height)
                        {
                            col = 0;
                            row = 0;
                        }
                    }
                }


                Rectangle r = new Rectangle();
                r.X = col * tileSize.Width;
                r.Y = row * tileSize.Height;
                r.Width = tileSize.Width;
                r.Height = tileSize.Height;

                float scaleX = (float)(tileSize.Width) / (float)(64.0f);
                float scaleY = (float)(tileSize.Height) / (float)(64.0f);

                texture.Draw(imageID, 0, 0, scaleX, scaleY, r, 0, 0, 0.0f, 255, 255, 255, 255);

            }
            d3d.SpriteEnd();
            d3d.DeviceEnd();
            d3d.Present(selectedPreviewPanel);
        }


        private void paintToolRadioButton_Click(object sender, EventArgs e)
        {
            if(paintToolRadioButton.Checked)
                paintTool = true;
        }

        private void selectionToolRadioButton_Click(object sender, EventArgs e)
        {
            if (selectionToolRadioButton.Checked)
                paintTool = false;
        }

        private void panel1_MouseClick(object sender, MouseEventArgs e)
        {
            if (((e.X-tileSetPos.X) / tileSize.Width) < tileSet.Width && ((e.Y-tileSetPos.Y) / tileSize.Height) < tileSet.Height)
            {
                coppiedTile = new Tile();//tileMap[e.X / tileSize.Width, e.Y / tileSize.Height];
                coppiedTile.EventString = "";
                coppiedTile.ImageID = ((e.X-tileSetPos.X) / tileSize.Width) + (tileSet.Width * ((e.Y-tileSetPos.Y) / tileSize.Height));
                coppiedTile.Obstacle = false;
                coppiedTile.TerrainType = -1;//coppiedTile.ImageID;
                coppiedTile.XPos = -1;
                coppiedTile.YPos = -1;
                coppiedTile.EventIndex = -1;

                groupBox2.Enabled = true;
                if (groupBox3.Enabled == true)
                    paintToSelected.Enabled = true;
                coppiedEventComboBox.SelectedIndex = coppiedTile.EventIndex;
                coppiedTerrainTypeComboBox.SelectedIndex = coppiedTile.TerrainType;

            }
        }

        private void panel2_MouseClick(object sender, MouseEventArgs e)
        {

            if (((e.X-mapPos.X) / (tileSize.Width*scale)) < mapSize.Width && ((e.Y-mapPos.Y) / (tileSize.Height*scale)) < mapSize.Height && tileSet != new Size(0, 0))
            {
                if (paintTool)
                {
                    selectedTile = tileMap[(e.X-mapPos.X) / (int)(tileSize.Width*scale), (e.Y-mapPos.Y) / (int)(tileSize.Height*scale)];

                    if (coppiedTile != null)
                    {
                        selectedTile.EventString = coppiedTile.EventString;
                        selectedTile.ImageID = coppiedTile.ImageID;
                        selectedTile.Obstacle = coppiedTile.Obstacle;
                        selectedTile.TerrainType = coppiedTile.TerrainType;
                        selectedEventComboBox.SelectedIndex = coppiedEventComboBox.SelectedIndex;
                        selectedTerrainTypeComboBox.SelectedIndex = coppiedTerrainTypeComboBox.SelectedIndex;
                        selectedTile.EventIndex = coppiedEventComboBox.SelectedIndex;
                    }

                    groupBox3.Enabled = true;
                    copyButton.Enabled = true;
                    if (groupBox2.Enabled == true)
                        paintToSelected.Enabled = true;

                }
                else
                {
                    selectedTile = tileMap[(e.X - mapPos.X) / (int)(tileSize.Width*scale), (e.Y - mapPos.Y) / (int)(tileSize.Height*scale)];



                }
            }

            groupBox3.Enabled = true;
            copyButton.Enabled = true;
            if (groupBox2.Enabled == true)
                paintToSelected.Enabled = true;
            selectedEventComboBox.SelectedIndex = (int)(selectedTile.EventIndex);
            selectedTerrainTypeComboBox.SelectedIndex = selectedTile.TerrainType;

        }

        private void panel2_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseIsDown == true)
            {
                int x = (e.X-mapPos.X) / (int)(tileSize.Width*scale);
                int y = ((e.Y-mapPos.Y) / (int)(tileSize.Height*scale));

                if (x < mapSize.Width && y < mapSize.Height && x >= 0 && y >= 0)
                {
                    if (paintTool && coppiedTile != null)
                    {
                        selectedTile = tileMap[x, y];
                        selectedTile.EventString = coppiedTile.EventString;
                        selectedTile.ImageID = coppiedTile.ImageID;
                        selectedTile.Obstacle = coppiedTile.Obstacle;
                        selectedTile.TerrainType = coppiedTile.TerrainType;
                        selectedEventComboBox.SelectedIndex = coppiedEventComboBox.SelectedIndex;
                        selectedTerrainTypeComboBox.SelectedIndex = coppiedTerrainTypeComboBox.SelectedIndex;
                        selectedTile.EventIndex = coppiedEventComboBox.SelectedIndex;

                    }
                    else if (!paintTool)
                    {
                        selectedTile = tileMap[x, y];
                        selectedTiles.Add(tileMap[x,y]);
                    }
                }

                return;
            }

        }

        private void panel2_MouseUp(object sender, MouseEventArgs e)
        {
            mouseIsDown = false;
        }

        private void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            mouseIsDown = true;
            if(selectedTiles !=null)
                selectedTiles.Clear();
        }

        private void Form1_Resize_1(object sender, EventArgs e)
        {
            ResizeScrollBars();
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            tileSetPos.Y -= e.NewValue - e.OldValue;
        }

        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            tileSetPos.X -= e.NewValue - e.OldValue;
        }

        private void applyMapChangesButton_Click(object sender, EventArgs e)
        {
            Size previousSize = mapSize;

            Tile[,] previousMap = tileMap;

            mapSize = new Size((int)(mapSizeXNumericUpDown.Value), (int)(mapSizeYNumericUpDown.Value));

            tileMap = new Tile[mapSize.Width, mapSize.Height];

            for (int x = 0;x < mapSize.Width; x++)
            {
                for (int y = 0;y < mapSize.Height; y++)
                {
                    if (x < previousSize.Width && y < previousSize.Height)
                        tileMap[x, y] = previousMap[x, y];
                    else
                    {
                        tileMap[x, y] = new Tile();
                        tileMap[x, y].XPos = x;
                        tileMap[x, y].YPos = y;
                    }
                }
            }


            tileSize = new Size((int)(tileSizeXNumericUpDown.Value), (int)(tileSizeYNumericUpDown.Value));

            tileSet = new Size(texture.GetTextureWidth(imageID) / tileSize.Width, texture.GetTextureHeight(imageID) / tileSize.Height);

            scale = (float)(scaleNumericUpDown.Value);
            ResizeScrollBars();

            coppiedimageIDNumericUpDown.Maximum = (tileSet.Width * tileSet.Height) - 1;
            selectedImageIDNumericUpDown.Maximum = (tileSet.Width * tileSet.Height) - 1;

        }

        private void ResizeScrollBars()
        {
            if (imageID == -1)
                return;

            if (panel1.Width < texture.GetTextureWidth(imageID) + vScrollBar1.Width)
            {
                hScrollBar1.Maximum = texture.GetTextureWidth(imageID) +10+ vScrollBar1.Width - panel1.Width;
                hScrollBar1.Enabled = true;
            }
            else
            {
                tileSetPos.X = 0;
                hScrollBar1.Enabled = false;
            }

            if (panel1.Height < texture.GetTextureHeight(imageID) + hScrollBar1.Size.Height)
            {
                vScrollBar1.Maximum = texture.GetTextureHeight(imageID) +10+ hScrollBar1.Size.Height-panel1.Height;
                vScrollBar1.Enabled = true;
            }
            else
            {
                tileSetPos.Y = 0;
                vScrollBar1.Enabled = false;
            }

            if (panel2.Width < (mapSize.Width * tileSize.Width*scale) + vScrollBar2.Width)
            {
                hScrollBar2.Maximum = (int)(mapSize.Width * tileSize.Width * scale) + (int)(105) + (int)(vScrollBar2.Width) - panel2.Width;
                hScrollBar2.Enabled = true;
            }
            else
            {
                mapPos.X = 0;
                hScrollBar2.Enabled = false;
            }

            if (panel2.Height < (mapSize.Height * tileSize.Height*scale) + hScrollBar2.Height)
            {
                vScrollBar2.Maximum = (int)(mapSize.Height * tileSize.Height * scale) + (int)(105) + hScrollBar2.Height - panel2.Height;
                vScrollBar2.Enabled = true;
            }
            else
            {
                mapPos.Y = 0;
                vScrollBar1.Enabled = false;
            }

        }

        private void vScrollBar2_Scroll(object sender, ScrollEventArgs e)
        {
            mapPos.Y -= e.NewValue - e.OldValue;
        }

        private void hScrollBar2_Scroll(object sender, ScrollEventArgs e)
        {
            mapPos.X -= e.NewValue - e.OldValue;
        }

        private void paintToSelected_Click(object sender, EventArgs e)
        {
            //selectedTile.XPos =                         coppiedTile.XPos;
            //selectedTile.YPos =                         coppiedTile.YPos;
            selectedTile.EventString =                  coppiedTile.EventString;
            selectedTile.ImageID =                      coppiedTile.ImageID;
            selectedTile.Obstacle =                     coppiedTile.Obstacle;
            selectedTile.TerrainType =                  coppiedTile.TerrainType;
            selectedEventComboBox.SelectedIndex =       coppiedEventComboBox.SelectedIndex;
            selectedTerrainTypeComboBox.SelectedIndex = coppiedTerrainTypeComboBox.SelectedIndex;
            selectedTile.EventIndex = coppiedTile.EventIndex;

            if (selectedTiles != null)
            {
                for (int i = 0; i < selectedTiles.Count; i++)
                {
                    //selectedTiles[i].XPos = coppiedTile.XPos;
                    //selectedTiles[i].YPos = coppiedTile.YPos;
                    selectedTiles[i].EventString = coppiedTile.EventString;
                    selectedTiles[i].ImageID = coppiedTile.ImageID;
                    selectedTiles[i].Obstacle = coppiedTile.Obstacle;
                    selectedTiles[i].TerrainType = coppiedTile.TerrainType;
                    selectedTiles[i].EventIndex = coppiedTile.EventIndex;
                }
            }

        }

        private void copyButton_Click(object sender, EventArgs e)
        {
            groupBox2.Enabled = true;
            if (groupBox3.Enabled == true)
                paintToSelected.Enabled = true;

            if (coppiedTile == null)
                coppiedTile = new Tile();

            coppiedTile.XPos = selectedTile.XPos;
            coppiedTile.YPos = selectedTile.YPos;
            coppiedTile.EventString = selectedTile.EventString;
            coppiedTile.ImageID = selectedTile.ImageID;
            coppiedTile.Obstacle = selectedTile.Obstacle;
            coppiedTile.TerrainType = selectedTile.TerrainType;
            coppiedTile.EventIndex = selectedEventComboBox.SelectedIndex;

            coppiedEventComboBox.SelectedIndex = selectedEventComboBox.SelectedIndex;
            coppiedTerrainTypeComboBox.SelectedIndex = selectedTerrainTypeComboBox.SelectedIndex;

        }

        

        public void UpdateInterface()
        {
            if (coppiedTile != null)
            {
                coppiedXLabel.Text = coppiedTile.XPos.ToString();
                coppiedYLabel.Text = coppiedTile.YPos.ToString();
                coppiedimageIDNumericUpDown.Value = coppiedTile.ImageID;
                //coppiedEventComboBox.SelectedIndex = -1;
                //coppiedEventComboBox.SelectedIndex = (int)(coppiedTile.EventIndex);
                //coppiedEventComboBox.SelectedItem = coppiedTile.EventString;
                coppiedObsCheckBox.Checked = coppiedTile.Obstacle;

            }

            if (selectedTile != null)
            {
                selectedXLabel.Text = selectedTile.XPos.ToString();
                selectedYLabel.Text = selectedTile.YPos.ToString();
                selectedImageIDNumericUpDown.Value = selectedTile.ImageID;
                //selectedEventComboBox.SelectedValue = selectedTile.EventString;
                //if (selectedTile.EventIndex == -1)
                //    selectedEventComboBox.SelectedValue = "";
                selectedObsCheckBox.Checked = selectedTile.Obstacle;
            }
        }

        private void coppiedTerrainTypeComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            coppiedTile.TerrainType = coppiedTerrainTypeComboBox.SelectedIndex;
        }

        private void coppiedimageIDNumericUpDown_ValueChanged(object sender, EventArgs e)
        {
            coppiedTile.ImageID = (int)(coppiedimageIDNumericUpDown.Value);
        }

        private void coppiedObsCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            coppiedTile.Obstacle = coppiedObsCheckBox.Checked;
        }

        private void selectedTerrainTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectedTile.TerrainType = selectedTerrainTypeComboBox.SelectedIndex;

            if (selectedTiles == null)
                return;

            for (int i = 0; i < selectedTiles.Count; i++)
            {
                selectedTiles[i].TerrainType = selectedTerrainTypeComboBox.SelectedIndex;
            }

        }

        private void selectedImageIDNumericUpDown_ValueChanged(object sender, EventArgs e)
        {
            selectedTile.ImageID = (int)(selectedImageIDNumericUpDown.Value);

            if (selectedTiles == null)
                return;

            for (int i = 0; i < selectedTiles.Count; i++)
            {
                selectedTiles[i].ImageID = (int)(selectedImageIDNumericUpDown.Value);
            }

        }



        private void selectedObsCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            selectedTile.Obstacle = selectedObsCheckBox.Checked;

            for (int i = 0; i < selectedTiles.Count; i++)
            {
                selectedTiles[i].Obstacle = selectedObsCheckBox.Checked;
            }

        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mapSize = new Size(10, 10);
            tileSize = new Size(64, 64);
            //tileSet = Size.Empty;
            tileMap = new Tile[10, 10];

            for (int x = 0; x < mapSize.Width; x++)
            {
                for (int y = 0; y < mapSize.Height; y++)
                {
                    tileMap[x, y] = new Tile();
                    tileMap[x, y].XPos = x;
                    tileMap[x, y].YPos = y;                    
                }
            }

            selectedTile = null;
            coppiedTile = null;
            //fileName = null;
            selectedTiles.Clear();
            mapPos = new Point(0, 0);
            tileSetPos = new Point(0, 0);
            //imageID = -1;
            //mapSizeXNumericUpDown.Value = mapSize.Width;
            //mapSizeYNumericUpDown.Value = mapSize.Height;
            //tileSizeXNumericUpDown.Value = tileSize.Width;
            //tileSizeYNumericUpDown.Value = tileSize.Height;

            //groupBox4.Enabled = false;
            groupBox3.Enabled = false;
            groupBox2.Enabled = false;
            //groupBox1.Enabled = false;
            copyButton.Enabled = false;
            paintToSelected.Enabled = false;

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveMapDialog = new SaveFileDialog();
            saveMapDialog.Filter = "All Files|*.*|Xml Files|*.xml";
            saveMapDialog.FilterIndex = 2;
            saveMapDialog.DefaultExt = "xml";

            if (saveMapDialog.ShowDialog() == DialogResult.OK)
            {
                XElement root = new XElement("tilemanager");

                XElement tm = new XElement("tm");
                root.Add(tm);

                XAttribute sizeX = new XAttribute("sizeX", mapSize.Width);
                tm.Add(sizeX);

                XAttribute sizeY = new XAttribute("sizeY", mapSize.Height);
                tm.Add(sizeY);

                XAttribute tilesizeX = new XAttribute("tileSizeX", tileSize.Width);
                tm.Add(tilesizeX);

                XAttribute tilesizeY = new XAttribute("tileSizeY", tileSize.Height);
                tm.Add(tilesizeY);

                XAttribute posX = new XAttribute("posX", 0);
                tm.Add(posX);

                XAttribute posY = new XAttribute("posY", 0);
                tm.Add(posY);

                XAttribute numRows = new XAttribute("numRows", tileSet.Height);
                tm.Add(numRows);

                XAttribute numCols = new XAttribute("numCols", tileSet.Width);
                tm.Add(numCols);

                XAttribute scaleX = new XAttribute("scale", this.scale);
                tm.Add(scaleX);

                //XAttribute imageFile = new XAttribute("imageFile", this.fileName);
                //tm.Add(imageFile);

                tm.Value = fileName;

                for (int x = 0; x < mapSize.Width; x++)
                {
                    for (int y = 0; y < mapSize.Height; y++)
                    {
                        XElement tile = new XElement("tile");
                        root.Add(tile);

                        XAttribute terrain = new XAttribute("terrainType", tileMap[x, y].TerrainType);
                        tile.Add(terrain);

                        XAttribute xPos = new XAttribute("xPos", tileMap[x, y].XPos);
                        tile.Add(xPos);

                        XAttribute yPos = new XAttribute("yPos", tileMap[x, y].YPos);
                        tile.Add(yPos);

                        XAttribute imageIDXml = new XAttribute("imageID", tileMap[x, y].ImageID);
                        tile.Add(imageIDXml);

                        XAttribute obs = null;
                        if (tileMap[x, y].Obstacle)
                            obs = new XAttribute("obstacle", 1);
                        else
                            obs = new XAttribute("obstacle", 0);
                        tile.Add(obs);

                        XAttribute eventIndex = new XAttribute("eventIndex", tileMap[x, y].EventIndex);
                        tile.Add(eventIndex);

                        if(tileMap[x,y].EventString != null)
                            tile.Value = tileMap[x, y].EventString;

                    }
                }



                root.Save(saveMapDialog.FileName);
                
            }

        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            loadMapDialog = new OpenFileDialog();
            loadMapDialog.Filter = "All Files|*.*|Xml Files|*.xml";
            loadMapDialog.FilterIndex = 2;
            loadMapDialog.DefaultExt = "xml";

            if (loadMapDialog.ShowDialog() == DialogResult.OK)
            {
                XElement root = XElement.Load(loadMapDialog.FileName);

                XElement tm = root.Element("tm");

                mapSize.Width = int.Parse(tm.Attribute("sizeX").Value);
                mapSize.Height = int.Parse(tm.Attribute("sizeY").Value);
                tileSize.Width = int.Parse(tm.Attribute("tileSizeX").Value);
                tileSize.Height = int.Parse(tm.Attribute("tileSizeY").Value);
                mapPos.X = int.Parse(tm.Attribute("posX").Value);
                mapPos.Y = int.Parse(tm.Attribute("posY").Value);
                tileSet.Height = int.Parse(tm.Attribute("numRows").Value);
                tileSet.Width = int.Parse(tm.Attribute("numCols").Value);
                scale = float.Parse(tm.Attribute("scale").Value);
                fileName = tm.Value;

                string fullPathAndName = filePath + "\\" + fileName;

                imageID = texture.LoadTexture(fullPathAndName, Color.FromArgb(255, 255, 255, 255).ToArgb());

                tileSet = new Size(texture.GetTextureWidth(imageID) / tileSize.Width, texture.GetTextureHeight(imageID) / tileSize.Height);

                coppiedimageIDNumericUpDown.Maximum = (tileSet.Width * tileSet.Height) - 1;
                selectedImageIDNumericUpDown.Maximum = (tileSet.Width * tileSet.Height) - 1;

                groupBox4.Enabled = true;
                groupBox1.Enabled = true;

                ResizeScrollBars();

                tileMap = new Tile[mapSize.Width,mapSize.Height];

                //XElement tile = tile.               

                IEnumerable<XElement> tiles = root.Elements("tile");

                for (int x = 0; x < mapSize.Width; x++)
                {
                    for (int y = 0; y < mapSize.Height; y++)
                    {
                        tileMap[x, y] = new Tile();

                        XElement tile = tiles.ElementAt((x*mapSize.Width) + (y));

                        tileMap[x, y].EventIndex = int.Parse(tile.Attribute("eventIndex").Value);
                        tileMap[x,y].EventString = tile.Value;
                        tileMap[x,y].ImageID = int.Parse(tile.Attribute("imageID").Value);

                        int tempB = int.Parse(tile.Attribute("obstacle").Value);
                        if (tempB != 0)
                            tileMap[x, y].Obstacle = true;
                        else
                            tileMap[x, y].Obstacle = false;

                        tileMap[x,y].TerrainType = int.Parse(tile.Attribute("terrainType").Value);
                        tileMap[x,y].XPos = int.Parse(tile.Attribute("xPos").Value);
                        tileMap[x,y].YPos = int.Parse(tile.Attribute("yPos").Value);

                        //tile = tile.NextNode.ElementsAfterSelf().First();
                    }
                }

                selectedTile = null;
                coppiedTile = null;
                selectedTiles.Clear();
                tileSetPos = new Point(0, 0);
                groupBox3.Enabled = false;
                groupBox2.Enabled = false;
                copyButton.Enabled = false;
                paintToSelected.Enabled = false;

            }
        }

        private void coppiedEventComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            coppiedTile.EventIndex = coppiedEventComboBox.SelectedIndex;
            if (coppiedTile.EventIndex != -1)
                coppiedTile.EventString = coppiedEventComboBox.Items[coppiedTile.EventIndex].ToString();
            else
                coppiedTile.EventString = "";
        }

        private void selectedEventComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            selectedTile.EventIndex = selectedEventComboBox.SelectedIndex;

            if (selectedTile.EventIndex != -1)
                selectedTile.EventString = selectedEventComboBox.Items[selectedTile.EventIndex].ToString();
            else
                selectedTile.EventString = "";
                
            //selectedTile.EventString = selectedEventComboBox.Items[selectedTile.EventIndex].ToString();

            if (selectedTiles == null)
                return;

            for (int i = 0; i < selectedTiles.Count; i++)
            {
                selectedTiles[i].EventIndex = selectedEventComboBox.SelectedIndex;
                if (selectedTiles[i].EventIndex != -1)
                    selectedTiles[i].EventString = selectedEventComboBox.Items[selectedTiles[i].EventIndex].ToString();
                else
                    selectedTiles[i].EventString = "";
            }
        }
        
    }
}
